//
//  WBUserAccount.swift
//  CFZWeiBo
//
//  Created by Cedric Zheng on 27/11/2016.
//  Copyright © 2016 Cedric Zheng. All rights reserved.
//

import UIKit

let userAccountKey = "userAccountKey"

/// Shared user account
let userAccountShared = WBUserAccount.shared

class WBUserAccount: NSObject {

    static let shared:WBUserAccount = WBUserAccount()
    
    /// The name that show on screen
    var screen_name: String?
    /// User identifier
    var uid: String?
    /// Token to access user data
    var access_token: String?
    /// User icon's url string
    var avatar_large: String?
    /// Time interval before the access token expires
    var expires_in: Double = 0 {
        didSet {
            expires_date = Date(timeInterval: expires_in, since: Date())
        }
    }
    /// The date that access token expires
    var expires_date: Date?
    /// Indicates if user has login
    var hasLogin: Bool {
        return access_token != nil && expires_date!.compare(Date()) == .orderedDescending
    }
    
    override var description: String {
        return dictionaryWithValues(forKeys: ["screen_name", "uid", "access_token", "avatar_large", "expires_date"]).description
    }
    
    override init() {
        super.init()
        
        read()
    }
    
    
    /// Save user data(Dictionary) to userDefault
    ///
    /// - Parameter dict: a dictionary with user data
    func save(_ dict: [String: Any]) {
        setValuesForKeys(dict)
        
        let userAccountDict = dictionaryWithValues(forKeys: ["screen_name", "uid", "access_token", "avatar_large", "expires_date"])
        
        UserDefaults.standard.set(userAccountDict, forKey: userAccountKey)
    }

    /// Reads from userDefault to gain user data
    func read() {
        if let userDict = userStandard.value(forKey: userAccountKey) as? [String: Any] {
            setValuesForKeys(userDict)
        }
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
    }
}
